# -*- encoding: utf-8 -*-
"""
    Created by Rachel on 2025/03/06
"""
import os
import pkgutil
from contextlib import contextmanager

import sqlalchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy



class SQLAlchemy(_SQLAlchemy):
    @contextmanager
    def auto_commit(self, throw=True):
        try:
            yield
            self.session.commit()
        except Exception as e:
            self.session.rollback()
            print("%r" % e)
            if throw:
                raise e


db: sqlalchemy = SQLAlchemy()


def init_databases(app: Flask):
    db.init_app(app)
    # # 如果api中未导入模型文件，初始化数据库时需导入一下模型文件
    import_models()
    with app.app_context():
        db.create_all()

def import_models():
    """导入模型"""
    pkg_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "models")
    pkg_name = os.path.basename(pkg_path)
    for _, file, is_pkg in pkgutil.walk_packages([pkg_path], "applications." + pkg_name + "."):
        if not is_pkg:
            __import__(file)